<template>
	<div>
		<div class="w-screen text-center bg-blue-400 p-4 text-2xl">登 录</div>
		<div>
			<div class="text-center my-2">
				<van-image round width="5rem" height="5rem" src="https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg" />
			</div>

			<van-form @submit="onSubmit">
				<van-cell-group inset>
					<van-field
						v-model="user.phone"
						name="电话号码"
						label="电话号码"
						placeholder="电话号码"
						:rules="[{ required: true, message: '请填写电话号码' }]"
					/>
					<van-field
						v-model="user.password"
						type="password"
						name="密码"
						label="密码"
						placeholder="密码"
						:rules="[{ required: true, message: '请填写密码' }]"
					/>
				</van-cell-group>
				<div style="margin: 16px">
					<div class="my-1"><van-button round block type="primary" native-type="submit"> 提交 </van-button></div>
					<div class="my-1"><van-button round block type="warning" @click="toRegister"> 去注册 </van-button></div>
				</div>
			</van-form>
		</div>
	</div>
</template>

<script setup>
import { reactive } from "vue";
import { login } from "@/api/user.js";
import { useRouter } from "vue-router";
import { showToast } from "vant";

const user = reactive({
	phone: "",
	password: "",
});

let router = useRouter();
const onSubmit = async () => {
	const res = await login({
		phone: user.phone,
		password: user.password,
	});
	if (res) {
		localStorage.setItem("token", res.data.token);
		localStorage.setItem("name", res.data.name);
		localStorage.setItem("phone", res.data.phone);
		showToast({
			message: "登录成功",
			type: "success",
			onClose: () => {
				router.push("/");
			},
		});
	}
};
const toRegister = () => {
	router.push("/register");
};
</script>

<style scoped></style>
